package com.rpc.center.server;

import com.rpc.center.entity.configure.RegisterCenterConfigure;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.jca.context.SpringContextResourceAdapter;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.*;

@Service
public class SocketCenterServerImpl implements CenterServer {
    @Autowired
    private RegisterCenterConfigure configure;
    @Autowired
    DefaultListableBeanFactory defaultListableBeanFactory;

    private ThreadPoolExecutor executor;

    /**
     * 启动注册服务器
     */
    public void startServer() throws IOException {
        ServerSocket serverSocket = new ServerSocket(configure.getPort(), 1024, InetAddress.getByName(configure.getAddress()));
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
                           public void run() {
                               System.out.println("-------注册中心服务器运行中--------");
                           }
                       }, 1000, 5000
        );
        while (true) {
            Socket socket = serverSocket.accept();
            CenterSocketHandler handler=new CenterSocketHandler();
            handler.setSocket(socket);
            executor.submit(handler);
        }
    }

    /**
     * 初始化注册服务器
     *
     * @return
     */
    public boolean init() {
        if (configure == null) {
            return false;
        }

        BlockingQueue<Runnable> queue = new ArrayBlockingQueue<>(512);
        RejectedExecutionHandler policy = new ThreadPoolExecutor.DiscardPolicy();
        //确定线程池大小
        int minPoolSize = configure.getMinPoolSize() > 1 ? configure.getMinPoolSize() : 2;
        int maxPoolSize = configure.getMaxPoolSize() < 20 ? configure.getMaxPoolSize() : 20;
        if (maxPoolSize < minPoolSize) {
            maxPoolSize = minPoolSize;
        }

        this.executor = new ThreadPoolExecutor(minPoolSize, maxPoolSize,
                0, TimeUnit.SECONDS,
                queue,
                policy);

        return true;
    }
}
